package com.zlm.weather.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.zlm.weather.constant.RedisEnum;
import com.zlm.weather.pojo.WeatherResponse;
import com.zlm.weather.service.WeatherService;
import com.zlm.weather.util.ConfigProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author: 郑
 * @Date: Create in 2020-1-16.
 */
@Service
public class WeatherServiceImpl implements WeatherService {
    @Autowired
    private ConfigProperties configProperties;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public String getDataByCityId(String cityId) {
        String result = HttpUtil.get( configProperties.getWeather_url() +"citykey="+ cityId);
        System.out.println("result:"+result);
        WeatherResponse weatherResponse = JSON.parseObject(result, WeatherResponse.class);
        return result;
    }

    @Override
    public WeatherResponse getDataByCityName(String cityName) {
        WeatherResponse result = (WeatherResponse)redisTemplate.opsForValue().get(RedisEnum.WEATHER.getKey() + cityName);
        if (null == result) {
            //防止高并发，加锁
            synchronized (this){
                if (null == result) {
                    String response = HttpUtil.get(configProperties.getWeather_url() +"city="+ cityName);
                    result = JSON.parseObject(response, WeatherResponse.class);
                    save(RedisEnum.WEATHER.getKey()+cityName,result,configProperties.getWeather_timeout());
                }else {
                    result = (WeatherResponse)redisTemplate.opsForValue().get(RedisEnum.WEATHER.getKey() + cityName);
                }
            }
        }
        return result;
    }

    //存入redis
    private void save(String key,Object value,String time){
        redisTemplate.opsForValue().set(key,value,Long.valueOf(time), TimeUnit.HOURS);

    }
}
